package com.lcc.lynx.base.system.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FTPUtil {

    public static final String LOCAL_DIRECTORY = "D:/myproject/idea/my/mySys/common/target/temp/";
    private static String HOST = "121.199.69.177"; // FTP服务器地址
    private static int PORT = 21; // FTP服务器端口
    private static String USERNAME = "mysys"; // FTP用户名
    private static String PASSWORD = "srXEjWs4JJh6MhnB"; // FTP密码

    public static void main(String[] args) {
        uploadFile("C:/Users/lcc/Pictures/lcc.png", "/user/picture");
    }

    public static boolean uploadFile(String localFilePath, String remoteDirectory) {

        FTPClient ftpClient = new FTPClient();
        boolean done = false;
        try {
            ftpClient.connect(HOST, PORT);
            ftpClient.login(USERNAME, PASSWORD);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            File localFile = new File(localFilePath);
            FileInputStream inputStream = new FileInputStream(localFile);

            // 判断目录是否存在，不存在则创建目录
            String[] split = remoteDirectory.split("[/\\\\]");
            for (String s : split) {
                if (!s.equals("")) {
                    if (!ftpClient.changeWorkingDirectory(s)) {
                        ftpClient.makeDirectory(s);
                    }
                    ftpClient.changeWorkingDirectory(s);
                }
            }

            System.out.println("开始上传文件: " + localFile.getName());
            done = ftpClient.storeFile( localFile.getName(), inputStream);
            inputStream.close();
            if (done) {
                System.out.println("文件上传成功！");
            }else{
                System.out.println("文件上传失败！");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return done;
    }


}
